<template>
  <basic-dialog
    :width="'60%'"
    :visible.sync="trackVisible"
    :title="'追踪'"
    :handle-close="handleCloseDialog"
    :handle-opened="handleOpenDialog"
    :showFooter="false"
  >
    <el-form
      ref="formData"
      v-loading="formLoading"
      :model="formData"
      label-width="135px"
      class="table_form_wrap"
    >
      <el-form-item label="问题类型" prop="problemTypeRelationList">
        <el-select
          v-model="formData.problemTypeRelationList"
          multiple
          placeholder="请选择问题类型"
          @change="handleProblemTypeChange"
        >
          <el-option
            v-for="item in problemOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="问题公司"
        prop="problemCompanyId"
        :rules="{
          required: !isNoProblem && !formData.departmentId,
          message: '问题公司不能为空',
          trigger: 'change'
        }"
      >
        <el-select
          v-model="formData.problemCompanyId"
          filterable
          remote
          clearable
          :remote-method="queryCompanyDataAction"
          :loading="companyLoading"
          @change="handleCompanyChange"
          placeholder="请输入问题公司"
        >
          <el-option
            v-for="item in companyOptions"
            :key="item.companyId"
            :label="item.companyName"
            :value="item.companyId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="集团商品管理中心"
        prop="departmentId"
        :rules="{
          required: !isNoProblem && !formData.problemCompanyId,
          message: '集团商品管理中心不能为空',
          trigger: 'change'
        }"
      >
        <el-select
          filterable
          v-model="formData.departmentId"
          @change="handleCenterChange"
          placeholder="请选择集团商品管理中心"
        >
          <el-option
            v-for="item in managementCenterOptions"
            :key="item.departmentId"
            :label="item.departmentName"
            :value="item.departmentId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="问题区域" prop="problemArea">
        <el-input readonly v-model.trim="formData.problemArea" />
      </el-form-item>
      <el-form-item
        label="问题责任人"
        prop="problemDutyUserId"
        :rules="{ required: !isNoProblem, message: '问题责任人不能为空', trigger: 'change' }"
      >
        <el-select
          v-model="formData.problemDutyUserId"
          filterable
          remote
          clearable
          :remote-method="queryUserDataAction"
          :loading="userLoading"
          @change="handleUserChange"
          placeholder="请输入问题责任人"
        >
          <el-option
            v-for="item in userOptions"
            :key="item.employeeId"
            :label="`${item.fname}(${item.fpsncode})`"
            :value="item.employeeId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="追踪说明"
        prop="trackingExplain"
        :rules="{ required: !isNoProblem, message: '追踪说明不能为空', trigger: 'change' }"
      >
        <el-input
          type="textarea"
          v-model.trim="formData.trackingExplain"
          placeholder="请输入追踪说明"
          show-word-limit
          maxlength="500"
          rows="4"
        />
      </el-form-item>
    </el-form>
    <el-row type="flex" justify="end">
      <el-button
        :loading="submitLoading"
        type="primary"
        @click="handleSubmit(1)"
      >追踪</el-button>
      <el-button
        :loading="submitLoading"
        @click="handleSubmit(0)"
      >暂存</el-button>
    </el-row>
  </basic-dialog>
</template>
<script>
import BasicDialog from '@/components/BasicDialog';
import {
  submitTrackService,
  queryCompanyAreaService,
  queryCompanyUserService,
  queryTrackDetailService,
  queryProblemTypeService,
  queryManagementCenterService
} from '@api/purchase/abnormalPurchase';

export default {
  components: {
    BasicDialog
  },
  props: {
    trackVisible: {
      type: Boolean,
      default: false
    },
    isSameTrack: {
      type: Boolean,
      default: false
    },
    selectIds: {
      type: Array,
      required: true
    }
  },
  data () {
    return {
      formLoading: false,
      userLoading: false,
      companyLoading: false,
      submitLoading: false,
      formData: {
        problemTypeRelationList: [],
        problemCompany: '',
        problemCompanyId: '',
        problemDutyUser: '',
        problemDutyUserId: '',
        problemArea: '',
        trackingExplain: '',
        departmentId: '',
        departmentName: '',
      },
      problemOptions: [],
      userOptions: [],
      companyOptions: [],
      managementCenterOptions: [],
    };
  },
  computed: {
    // 问题类型只有无问题
    isNoProblem () {
      const { problemTypeRelationList } = this.formData;
      return problemTypeRelationList.length == 1 && problemTypeRelationList.includes(20);
    }
  },
  methods: {
    handleProblemTypeChange () {
      if (this.isNoProblem) { // 无问题
        this.$refs.formData.clearValidate()
      }
    },
    handleOpenDialog () {
      this.queryProblemTypeAction()
      this.queryManagementCenterAction()
      if (this.isSameTrack) {
        this.queryTrackDetailAction()
      }
    },
    // 获取追踪详情
    async queryTrackDetailAction () {
      const res = await queryTrackDetailService({ idList: this.selectIds }, state => { this.formLoading = state });
      if (res?.data) {
        const { problemCompany, problemCompanyId, problemDutyUser, problemDutyUserId, problemDutyUserCode, problemArea } = res.data;
        if (problemCompanyId) {
          this.companyOptions = [
            { companyId: problemCompanyId, companyName: problemCompany, saleAreaName: problemArea }
          ]
        }
        if (problemDutyUserId) {
          this.userOptions = [
            { fname: problemDutyUser, employeeId: problemDutyUserId, fpsncode: problemDutyUserCode }
          ]
        }
        this.formData = {
          ...res.data
        };
      }
    },
    // 问题类型下拉
    async queryProblemTypeAction () {
      const res = await queryProblemTypeService();
      if (res?.data) {
        this.problemOptions = res.data;
      }
    },
    // 商品管理区域
    async queryManagementCenterAction () {
      const res = await queryManagementCenterService();
      if (res?.data) {
        this.managementCenterOptions = res.data;
      }
    },
    // 责任人下拉
    async queryUserDataAction (param) {
      const res = await queryCompanyUserService({ nameLike: param }, state => { this.userLoading = state });
      if (res?.data) {
        this.userOptions = res.data;
      }
    },
    // 公司下拉
    async queryCompanyDataAction (param) {
      const res = await queryCompanyAreaService({ nameLike: param }, state => { this.companyLoading = state });
      if (res?.data) {
        this.companyOptions = res.data;
      }
    },
    // 公司切换
    handleCompanyChange (val) {
      if (val) {
        const { saleAreaName, companyName } = this.companyOptions.find(item => item.companyId == val)
        this.formData.problemArea = saleAreaName
        this.formData.problemCompany = companyName
      } else {
        this.formData.problemArea = ''
        this.formData.problemCompany = ''
      }
      this.formData.departmentId = ''
      this.formData.departmentName = ''
    },
    // 管理中心切换
    handleCenterChange (val) {
      if (val) {
        const { saleAreaName, departmentName } = this.managementCenterOptions.find(item => item.departmentId == val)
        this.formData.problemArea = saleAreaName
        this.formData.departmentName = departmentName
      } else {
        this.formData.problemArea = ''
      }
      this.formData.problemCompany = ''
      this.formData.problemCompanyId = ''
    },
    // 人员切换
    handleUserChange (val) {
      if (val) {
        const { fname, fpsncode } = this.userOptions.find(item => item.employeeId == val)
        this.formData.problemDutyUser = fname
        this.formData.problemDutyUserCode = fpsncode
      } else {
        this.formData.problemDutyUser = ''
        this.formData.problemDutyUserCode = ''
      }
    },
    // 提交 1 or 暂存 0
    handleSubmit (type) {
      if (type == 0) {
        this.submitAction(type)
      } else {
        this.$refs['formData'].validate((valid) => {
          if (valid) {
            this.submitAction(type)
          }
        });
      }
    },
    async submitAction (type) {
      const param = {
        type,
        idList: this.selectIds,
        ...this.formData
      };
      const res = await submitTrackService(param, state => { this.submitLoading = state });
      if (res) {
        this.$message.success('操作成功')
        this.$emit('getTableData');
        this.handleCloseDialog();
      }
    },
    // 关闭弹框
    handleCloseDialog () {
      this.$refs.formData.resetFields();
      this.$emit('update:trackVisible', false);
    },
  }
};
</script>
